package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.entity.ApplicationInfo;
import com.leyou.auth.mapper.ApplicationInfoMapper;
import com.leyou.common.auth.pojo.AppInfo;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties jwtProp;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private ApplicationInfoMapper applicationInfoMapper;

    public void login(String username, String password, HttpServletRequest request, HttpServletResponse response) {
        //校验用户名和密码是否正确
        User user = userClient.findUserByUsernameAndPassword(username, password);
        //将User对象转成UserInfo对象
        UserInfo userInfo = new UserInfo(user.getId(), user.getUsername(), "admin");
        //生成token并写入cookie
        createTokenToCookie(request, response, userInfo);
    }

    //生成token并写入cookie
    private void createTokenToCookie(HttpServletRequest request, HttpServletResponse response, UserInfo userInfo) {
        //生成token
        String token = JwtUtils.generateTokenExpireInMinutes(userInfo, jwtProp.getPrivateKey(), jwtProp.getCookie().getExpire());
        //把token写入cookie
        CookieUtils.newCookieBuilder()
                .request(request)
                .response(response)
                .name(jwtProp.getCookie().getCookieName())
                .value(token)
                .domain(jwtProp.getCookie().getCookieDomain())
                .httpOnly(true)
                .build();
    }

    public UserInfo verify(HttpServletRequest request, HttpServletResponse response) {
        //从cookie中获取token
        String token = CookieUtils.getCookieValue(request, jwtProp.getCookie().getCookieName());
        //判空
        if(StringUtils.isEmpty(token)){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        //验证解析token
        Payload<UserInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
        }catch (Exception e){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        //判断当前token是否在黑名单
        Boolean isBlack = redisTemplate.hasKey(payload.getId());
        if(isBlack){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        UserInfo userInfo = payload.getUserInfo();
        //获取token的失效时间
        Date expDate = payload.getExpiration();
        //获取到刷新时间
        DateTime refreshTime = new DateTime(expDate).minusMinutes(jwtProp.getCookie().getRefreshTime());
        //判断如果当前时间在刷新时间之后，则重新生成token
        if(refreshTime.isBeforeNow()){
            //生成token并写入cookie
            createTokenToCookie(request, response, userInfo);
        }
        return userInfo;
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //获取cookie
        String token = CookieUtils.getCookieValue(request, jwtProp.getCookie().getCookieName());
        //判空
        if(StringUtils.isEmpty(token)){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        //验证解析token
        Payload<UserInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
        }catch (Exception e){
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        //获取token的id
        String tokenId = payload.getId();
        //获取token的过期时间
        long remainTime = payload.getExpiration().getTime() - System.currentTimeMillis();
        //如果剩余过期时间还有超过1秒，就把当前token放入redis黑名单中
        if(remainTime>1000){
            redisTemplate.opsForValue().set(tokenId, "随便写", remainTime, TimeUnit.MILLISECONDS);
        }
        //删除token
        CookieUtils.deleteCookie(jwtProp.getCookie().getCookieName(),
                jwtProp.getCookie().getCookieDomain(), response);
    }

    /**
     * 提供一个校验服务id和serviceName是否正确的方法
     */
    public Boolean isUsable(Long id, String serviceName){
        //先根据id查询App对象
        ApplicationInfo applicationInfo = applicationInfoMapper.selectById(id);
        if(applicationInfo==null){
            return false;
        }
        //比对app的密码
        boolean matches = passwordEncoder.matches(serviceName, applicationInfo.getSecret());
        if(matches){
             return true;
        }
        return false;
    }

    public String authorize(Long id, String serviceName) {
        //校验服务id和serviceName是否正确
        Boolean canUse = isUsable(id, serviceName);
        if(!canUse){
            log.error("【服务器{}获取token】失败，服务id或者服务名称不正确！", serviceName);
            throw new LyException(ExceptionEnum.INVALID_SERVER_ID_SECRET);
        }
        try {
            //获取当前服务器可以访问的服务列表
            List<Long> targetIdList = applicationInfoMapper.queryTargetIdList(id);
            //创建生成token的载荷对象
            AppInfo appInfo = new AppInfo(id, serviceName, targetIdList);
            //生成token
            String token = JwtUtils.generateTokenExpireInMinutes(appInfo, jwtProp.getPrivateKey(), jwtProp.getApp().getExpire());
            return token;
        }catch (Exception e){
            log.error("【服务器{}获取token】失败，生成token异常！", serviceName);
            throw new LyException(ExceptionEnum.INVALID_SERVER_ID_SECRET);
        }

    }
}
